/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.dao;

import com.chinamobile.cmss.lakehouse.common.enums.UserType;
import com.chinamobile.cmss.lakehouse.dao.entity.UserEntity;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface UserDao extends JpaRepository<UserEntity, Integer>, JpaSpecificationExecutor<UserEntity> {

    /**
     * find by user name
     *
     * @param userName user name
     * @return user
     */
    UserEntity findByUserName(String userName);

    /**
     * delete by user name
     *
     * @param userName user name
     */
    @Transactional
    void deleteByUserName(String userName);

    /**
     * find by user type
     *
     * @param userType user type
     * @return user list
     */
    List<UserEntity> findByUserType(UserType userType);

    /**
     * judge user name exists except user id
     *
     * @param userName user name
     * @param userId   user id
     * @return true if user name exists, otherwise return false
     */
    boolean existsByUserNameAndUserIdNot(String userName, String userId);

    /**
     * judge user name exists
     *
     * @param userName user name
     * @return true if user name exists, otherwise return false
     */
    boolean existsByUserName(String userName);

    /**
     * get user by user name and password
     *
     * @param userName     user name
     * @param userPassword user password
     * @return user
     */
    UserEntity findByUserNameAndUserPassword(String userName, String userPassword);

    /**
     * get user by token
     *
     * @param token user token
     * @return user
     */
    @Query(value = "select u from UserEntity u , UserAccessTokenEntity uat where u.userName = uat.userId and uat.token = ?1 and uat.expireTime > current_time")
    UserEntity findByToken(String token);

    /**
     * find user by user id
     *
     * @param userId
     * @return
     */
    Optional<UserEntity> findByUserId(String userId);

    /**
     * delete user by user id
     *
     * @param userId
     */
    void deleteByUserId(String userId);
}
